<template>
  <div class="account-management-container">
    <!-- 搜索和添加用户区域 -->
    <div class="bg-white p-4 rounded-t-lg">
      <div class="flex items-center justify-between">
        <div class="flex gap-2">
          <el-input v-model="searchParams.username" :placeholder="t('authority.account.userName')" clearable
            :prefix-icon="Search" />
          <el-input v-model="searchParams.email" :placeholder="t('authority.account.email')" clearable
            :prefix-icon="Message" />
          <el-button type="primary" @click="handleSearch">{{ t('authority.common.search') }}</el-button>
        </div>
        <el-button v-if="hasPermission('sys:user:save') || isSuperAdmin" @click="handleAddUser">
          {{ t('authority.account.addUser') }}
        </el-button>
      </div>
    </div>

    <!-- 用户列表表格 -->
    <div class="table-container bg-white p-4 rounded shadow-sm">
      <div class="table-wrapper">
        <el-table :data="tableData" border height="100%" v-loading="loading" class="adaptive-table" table-layout="auto"
          :header-cell-style="headerCellStyle">
          <!-- 数据列 - 完全自适应宽度 -->
          <el-table-column prop="username" :label="t('authority.account.userName')" min-width="120"
            class-name="data-column" />
          <el-table-column prop="email" :label="t('authority.account.email')" min-width="180"
            class-name="data-column" />
          <el-table-column prop="mobile" :label="t('authority.account.mobile')" min-width="120"
            class-name="data-column" />
          <el-table-column prop="role" :label="t('authority.account.role')" min-width="120" class-name="data-column" />
          <el-table-column prop="status" :label="t('authority.account.status')" min-width="100"
            class-name="data-column">
            <template #default="scope">
              <status-indicator :status="scope.row.status" :active-text="t('authority.account.active')"
                :inactive-text="t('authority.account.inactive')" />
            </template>
          </el-table-column>
          <el-table-column prop="createDate" :label="t('authority.account.createTime')" min-width="150"
            class-name="data-column" />
          <el-table-column prop="updateDate" :label="t('authority.account.modifyTime')" min-width="150"
            class-name="data-column" />
          <el-table-column prop="modifyUser" :label="t('authority.account.modifyUser')" min-width="120"
            class-name="data-column" />

          <!-- 操作列 - 固定宽度，始终在右侧 -->
          <el-table-column :label="t('authority.common.operation')" width="250" align="center" fixed="right"
            class-name="operation-column">
            <template #default="scope">
              <div class="operation-buttons">
                <el-button link type="primary"
                  v-if="hasPermission('sys:role:update') || hasAnyPermission(['sys:user:disable', 'sys:user:enable']) || isSuperAdmin"
                  @click="handleToggleStatus(scope.row)">
                  {{ scope.row.status === 1 ? t('authority.common.disable') : t('authority.common.enable') }}
                </el-button>
                <el-button link type="primary" v-if="hasPermission('sys:user:reset') || isSuperAdmin"
                  @click="handleReset(scope.row)">
                  {{ t('authority.account.resetPassword') }}
                </el-button>
                <el-button link type="primary" v-if="hasPermission('sys:user:update') || isSuperAdmin"
                  @click="handleModify(scope.row)">
                  {{ t('authority.common.modify') }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50,100]"
        layout="total, prev, pager, next, sizes, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 用户表单对话框组件 -->
    <user-form-dialog v-if="dialogVisible" v-model:visible="dialogVisible" :form-data="formData"
      :dialog-type="dialogType" @submit-success="handleDialogSuccess" />

    <!-- 重置密码对话框 -->
    <reset-password-dialog v-model:visible="resetDialogVisible" :email="currentEmail" @confirm="confirmResetPassword" />

    <!-- 禁用/启用账户对话框 -->
    <status-dialog v-model:visible="statusDialogVisible" :email="currentEmail" :action="currentAction"
      @confirm="confirmToggleStatus" />

    <!-- 创建成功密码提示对话框 -->
    <el-dialog v-model="passwordDialogVisible" :title="t('account.accountCreatedSuccess')" width="400px"
      :close-on-click-modal="false">
      <div class="password-success-content">
        <el-icon class="success-icon" color="#67C23A" size="48">
          <CircleCheckFilled />
        </el-icon>
        <p class="success-message">{{ t('account.accountCreatedMessage') }}</p>
        <p class="password-info">{{ t('account.passwordSentInfo') }}</p>
        <p class="email-address">{{ createdUserEmail }}</p>
        <p class="password-note">{{ t('account.passwordChangeNote') }}</p>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <el-button type="primary" @click="passwordDialogVisible = false">
            OK
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
// 账号管理页（Account Management）
// 职责：
// - 查询、分页展示账号列表
// - 新增 / 修改账号（弹窗）
// - 启用/禁用、重置密码等账号操作
// - 依据权限控制按钮可见性
import { ref, reactive, onMounted, defineAsyncComponent } from "vue";
import { Search, Message } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getUserList,
  addUser,
  updateUser,
  resetUserPassword,
  toggleUserStatus,
  deleteUser
} from "./data";
import { roleApi } from "@/api/authority";
import { useI18n } from "@/composables/useI18n";

const StatusIndicator = defineAsyncComponent(() => import("@/components/status-indicator/StatusIndicator.vue"));
import { useAppStore } from "@/store";
import { CircleCheckFilled } from "@element-plus/icons-vue";
import { usePermission } from "@/composables/usePermission";

const UserFormDialog = defineAsyncComponent(() => import("./components/UserFormDialog.vue"));
const ResetPasswordDialog = defineAsyncComponent(() => import("./components/ResetPasswordDialog.vue"));
const StatusDialog = defineAsyncComponent(() => import("./components/StatusDialog.vue"));

// 多语言
const { t } = useI18n();

// 当前登录用户信息（用于组织过滤、权限判断等）
const store = useAppStore();
const currentUser = store.state.user;
// 权限
const { hasPermission, hasAnyPermission, isSuperAdmin } = usePermission();

// 搜索参数
const searchParams = reactive({
  username: "",
  email: ""
});

// 表格数据
const tableData = ref<any[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表头样式：与设计稿一致的浅灰背景
const headerCellStyle = () => ({
  background: '#F5F6FA',
  color: '#111827',
  fontWeight: 600
});

// 角色列表数据
const roleList = ref<any[]>([]);

// 对话框控制
const dialogVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
const formData = ref({});

// 重置密码对话框
const resetDialogVisible = ref(false);
const currentEmail = ref("");
// 账户状态切换上下文使用 id 更稳妥
const currentUserId = ref<string | null>(null);

// 状态切换对话框
const statusDialogVisible = ref(false);
const currentAction = ref("");

// 创建成功密码提示对话框
const passwordDialogVisible = ref(false);
const createdUserEmail = ref("");

// 初始化
onMounted(() => {
  loadRoleList();
  loadTableData();
});

// 加载角色列表：用于在表格中映射 roleId → 角色名
const loadRoleList = async () => {
  try {
    // 权限校验：无列表查询权限则不请求，避免后端 403 报错
    if (!isSuperAdmin.value && !hasPermission('sys:user:page')) {
      if (import.meta.env.DEV) {
        // eslint-disable-next-line no-console
        console.warn('[Account] 无权限查看用户列表，已跳过请求。当前权限:', store.state.permissions);
      }
      tableData.value = [];
      total.value = 0;
      loading.value = false;
      ElMessage.warning('当前账号无权限查看用户列表');
      return;
    }
    const response = await roleApi.getList();
    if (response.code === 0) {
      roleList.value = response.data || [];
    }
  } catch (error) {
    console.error('加载角色列表失败:', error);
  }
};

// 加载表格数据：携带组织约束与检索条件
const loadTableData = async () => {
  loading.value = true;
  try {
    // 构建查询参数，包含组织约束
    const queryParams = {
      page: currentPage.value,
      limit: pageSize.value,
      username: searchParams.username,
      email: searchParams.email,
      // 添加组织约束：当前用户所在组织的账号
      organId: currentUser.organId || currentUser.deptId || null
    };

    const result = await getUserList(queryParams);

    // 处理数据，确保字段存在
    tableData.value = result.list.map((item: any) => {
      // 根据角色ID查找角色名称
      const rawRoleId = item.roleId ?? (Array.isArray(item.roleIdList) ? item.roleIdList[0] : undefined);
      const roleInfo = roleList.value.find((role: any) => String(role.id) === String(rawRoleId));
      const roleName = item.role || item.roleName || (roleInfo ? roleInfo.name || roleInfo.roleName : '-');

      return {
        ...item,
        mobile: item.mobile || '-', // 手机号为空时显示 '-'
        role: item.role || roleName, // 优先使用返回的角色名称，否则根据角色ID查找
        createDate: item.createDate || item.createTime || '-', // 兼容不同字段名
        updateDate: item.updateDate || item.modifyTime || '-', // 兼容不同字段名
        modifyUser: item.modifyUser || '-', // 修改用户为空时显示 '-'
      };
    });

    total.value = result.totalCount;
  } catch (error) {
    console.error('加载用户数据失败:', error);
    ElMessage.error('加载用户数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索：重置到第 1 页并重新加载
const handleSearch = () => {
  currentPage.value = 1;
  loadTableData();
};

// 分页：修改每页条数
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadTableData();
};

// 分页：跳转页码
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadTableData();
};

// 添加用户：打开对话框
const handleAddUser = () => {
  dialogType.value = "add";
  formData.value = {};
  dialogVisible.value = true;
};

// 修改用户：打开对话框并回填数据
const handleModify = (row: any) => {
  dialogType.value = "edit";
  formData.value = { ...row };

  // 检查是否为管理员账号，给出提示
  if (String(row.roleId ?? row.roleIdList?.[0]) === '1') {
    ElMessage.info(t('account.adminModifyTip'));
  }

  dialogVisible.value = true;
};

// 删除用户：二次确认 → 调用删除 → 刷新列表
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.username}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const result = await deleteUser(row.id);
    if (result.success) {
      ElMessage.success(result.message);
      loadTableData();
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error('删除用户失败:', error);
      ElMessage.error('删除用户失败');
    }
  }
};

// 重置密码：打开确认对话框
const handleReset = (row: any) => {
  currentEmail.value = row.email;
  resetDialogVisible.value = true;
};

// 确认重置密码：根据 email 定位用户 → 调用重置接口
const confirmResetPassword = async () => {
  try {
    // 这里需要根据实际需求获取用户ID
    const user = tableData.value.find((u: any) => u.email === currentEmail.value);
    if (!user) {
      ElMessage.error('用户不存在');
      return;
    }

    const result = await resetUserPassword(user.id, currentUser?.email || currentUser?.username || '');
    if (result.success) {
      ElMessage.success(result.message);
      resetDialogVisible.value = false;
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    console.error('重置密码失败:', error);
    ElMessage.error('重置密码失败');
  }
};

// 切换状态：打开确认对话框
const handleToggleStatus = (row: any) => {
  currentEmail.value = row.email;
  currentUserId.value = String(row.id ?? "");
  currentAction.value = row.status === 1 ? "disable" : "enable";
  statusDialogVisible.value = true;
};

// 确认切换状态：根据 email 定位用户 → 调用启用/禁用接口
const confirmToggleStatus = async () => {
  try {
    // 以 id 为准定位用户，避免 email 变更或重复导致取错
    const user = tableData.value.find((u: any) => String(u.id) === String(currentUserId.value));
    if (!user) {
      ElMessage.error('用户不存在');
      return;
    }

    const newStatus = user.status === 1 ? 0 : 1;
    const result = await toggleUserStatus(user.id, newStatus);
    if (result.success) {
      ElMessage.success(result.message);
      statusDialogVisible.value = false;
      loadTableData();
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    console.error('切换状态失败:', error);
    ElMessage.error('切换状态失败');
  }
};

// 账号表单提交成功回调：根据 isAdd 区分新增/更新
const handleDialogSuccess = async (formData: any) => {
  try {
    if (formData.isAdd) {
      // 添加
      const result = await addUser({ ...formData, modifyUser: currentUser?.email || currentUser?.username || '' });
      if (result.success) {
        // 创建成功后显示密码提示对话框
        createdUserEmail.value = formData.email;
        passwordDialogVisible.value = true;
        // 不显示默认的成功消息，因为会显示密码对话框
      } else {
        ElMessage.error(result.message);
      }
    } else {
      // 更新：按后端文档仅传 id、username、roleId（均为字符串）
      const payload = {
        id: String(formData.id),
        username: String(formData.username || ''),
        roleId: String(formData.roleId ?? formData.roleIdList?.[0] ?? '')
      };
      const result = await updateUser(payload as any);
      if (result.success) {
        // 根据是否包含角色信息给出不同的成功提示
        if (formData.roleId !== undefined) {
          ElMessage.success(t('account.updateSuccess'));
        } else {
          ElMessage.success(t('account.usernameUpdateSuccess'));
        }
      } else {
        ElMessage.error(result.message);
      }
    }

    dialogVisible.value = false;
    loadTableData();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
};
</script>

<style lang="scss" scoped>
.account-management-container {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-wrapper {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 16px;
}

.password-success-content {
  text-align: center;
  padding: 20px;
}

.success-icon {
  margin-bottom: 15px;
}

/* 表格样式 - 与设计稿一致 */
.adaptive-table {

  // 设置表格布局为自动，实现完全自适应
  :deep(.el-table) {
    table-layout: auto;
    --el-table-border-color: #E5E7EB; // 全局分隔线颜色
  }

  :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }

  // 表头：统一浅灰背景，深色文字，加粗，圆角
  :deep(.el-table__header-wrapper),
  :deep(.el-table__header-wrapper th),
  :deep(.el-table__header-wrapper tr),
  :deep(.el-table__header-wrapper .cell),
  :deep(.el-table__header-wrapper thead),
  :deep(.el-table__header-wrapper thead tr),
  :deep(.el-table__header-wrapper thead tr th) {
    background-color: #F5F6FA !important;
    color: #111827 !important;
    font-weight: 600;
    border-bottom: 1px solid #E5E7EB !important;
    padding: 10px 16px;
  }

  // 表头左右圆角
  :deep(.el-table__header-wrapper thead tr th:first-child) {
    border-top-left-radius: 8px;
  }

  :deep(.el-table__header-wrapper thead tr th:last-child) {
    border-top-right-radius: 8px;
  }

  // 顶部细线颜色
  :deep(.el-table__inner-wrapper::before) {
    background-color: #E5E7EB !important;
    height: 1px;
  }

  // 表体：白底，文字颜色，底部分隔线，内边距
  :deep(.el-table__body tr),
  :deep(.el-table__body td) {
    background-color: #ffffff !important;
  }

  :deep(.el-table__body .el-table__cell) {
    color: #374151;
    padding: 12px 16px;
    border-bottom: 1px solid #E5E7EB !important;
  }

  // 行 hover 效果
  :deep(.el-table__body tr:hover > td) {
    background: #F9FAFB !important;
  }

  // 数据列完全自适应宽度
  :deep(.data-column) {
    .cell {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: keep-all;
    }
  }

  // 操作列固定样式，确保始终在右侧
  :deep(.operation-column) {
    position: sticky;
    right: 0;
    z-index: 2;
    background-color: var(--el-table-bg-color);

    .cell {
      white-space: nowrap;
      overflow: hidden;
    }
  }

  // 操作按钮容器 - 链接风格
  .operation-buttons {
    display: flex;
    gap: 0;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;

    .el-button {
      flex-shrink: 0;
      min-width: auto;
      padding: 0 0; // 看起来像纯文本链接
      font-size: 13px;
      color: #0F766E; // 链接主色
    }

    .el-button:hover {
      color: #115E59;
      text-decoration: underline;
      background: transparent;
    }
  }

  // 确保固定列在斑马纹表格中也有正确的背景色
  :deep(.el-table__row:nth-child(even)) {
    .operation-column {
      background-color: var(--el-table-row-hover-bg-color);
    }
  }


}

// 响应式设计
@media (max-width: 768px) {
  .adaptive-table {
    :deep(.el-table__body-wrapper) {
      overflow-x: auto;
    }

    .operation-buttons {
      flex-direction: column;
      gap: 4px;

      .el-button {
        width: 100%;
        justify-content: center;
      }
    }
  }
}

.success-message {
  font-size: 18px;
  color: #303133;
  margin-bottom: 10px;
}

.password-info {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.email-address {
  font-size: 16px;
  color: #409EFF;
  font-weight: bold;
  margin-bottom: 10px;
}

.password-note {
  font-size: 12px;
  color: #909399;
}
</style>

<style lang="scss">
.el-pager li.is-active {
  border: 1px solid #107082;
}
</style>